/*
 * Created on 20.06.2003
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package ro.gateway.aida.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Hashtable;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.obj.Country;
import ro.gateway.aida.obj.County;
import ro.gateway.aida.obj.Region;
import ro.gateway.aida.obj.Town;
import ro.gateway.aida.obj.Village;
import ro.gateway.aida.obj.db.AIDALocationDB;
import ro.gateway.aida.obj.db.CountyDB;
import ro.gateway.aida.obj.db.RegionDB;
import ro.gateway.aida.obj.db.TownDB;
import ro.gateway.aida.obj.db.VillageDB;
import ro.gateway.aida.srv.EditorServlet;
import ro.gateway.aida.srv.ICFService;
import ro.gateway.aida.srv.IIDGenerator;
import ro.gateway.aida.utils.HttpUtils;



/**
 * @author Mihai Postelnicu
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */

/**
 * @author Mihai Postelnicu
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
public class EditLocationServlet extends EditorServlet
{
      public static final String PNAME_BEANS = "EDITING_LOCATIONS";
      public static final String JSP_PAGE = "location_editor.jsp";


      /**
       * @author Mihai Postelnicu
       * Creates common dropdowns for location selection
       * @param request
       * @param cfService
       */
      protected void generateCommon( HttpServletRequest request,
                                     ICFService cfService )
      {
            Hashtable bean = getBean( request );
            String del = ( String ) bean.get( "deletion" );
            String countysel = null;
            String townsel = null;
            String regionsel = null;
            String villagesel = null;
            PersistenceToken token = PersistenceManager.tokenLookup( getServletContext() );
            String countrysel = HttpUtils.getValidTrimedString( request,
                  "countrylist", null ); //country select

            if ( !( "region".equals( del ) ) )
                  regionsel = HttpUtils.getValidTrimedString( request,
                        "regionlist", null ); //region select


            if ( !( "county".equals( del ) ) )
                  countysel = HttpUtils.getValidTrimedString( request,
                        "countylist", null ); //county select

            if ( !( "town".equals( del ) ) )
                  townsel = HttpUtils.getValidTrimedString( request, "townlist",
                        null ); //town select

            if ( !( "village".equals( del ) ) )
                  villagesel = HttpUtils.getValidTrimedString( request, "villagelist",
                        null ); //village select


            String param = HttpUtils.getValidTrimedString( request, "param", null ); //action parameter

            if ( "countrysel".equals( param ) )
            {
                  regionsel = null;
                  countysel = null;
                  townsel = null;
            }

            if ( "regionsel".equals( param ) )
            {
                  countysel = null;
                  townsel = null;
            }

            if ( "countysel".equals( param ) )
            {
                  townsel = null;
            }

            //generate country list:
            if ( bean.get( "countrylist" ) == null )
            {
                  Country[] clist;

                  try
                  {
                        clist = AIDALocationDB.getManager( token ).getAllCountries();
                        beanSync( bean, "countrylist", clist );
                  }
                  catch ( Exception e )
                  {
                        e.printStackTrace();
                  }
            }

            //generate region list
            if ( countrysel != null )
            {
                  try
                  {
                        Region[] rlist;
                        rlist = RegionDB.getManager( token ).getAllByCountry( countrysel );
                        beanSync( bean, "regionlist", rlist );
                  }
                  catch ( SQLException e )
                  {
                        e.printStackTrace();
                  }
            }

            //generate county list
            if ( regionsel != null )
            {
                  try
                  {
                        County[] jlist;
                        jlist = CountyDB.getManager( token ).getForRegion(
                              Integer.parseInt( regionsel ) );
                        beanSync( bean, "countylist", jlist );
                  }
                  catch ( SQLException e )
                  {
                        e.printStackTrace();
                  }
                  catch ( NumberFormatException e )
                  {
                        e.printStackTrace();
                  }
            }

            //generate town list
            if ( countysel != null )
            {
                  try
                  {
                        Town[] olist;
                        olist = TownDB.getManager( token ).getAllForCounty(
                              Integer.parseInt( countysel ) );
                        beanSync( bean, "townlist", olist );
                  }
                  catch ( SQLException e )
                  {
                        e.printStackTrace();
                  }
                  catch ( NumberFormatException e )
                  {
                        e.printStackTrace();
                  }
            }

            //generate village list
            if ( townsel != null )
            {
                  try
                  {
                        Village[] llist;
                        llist = VillageDB.getManager( token ).getAllForTown(
                              Integer.parseInt( townsel ) );
                        beanSync( bean, "villagelist", llist );
                  }
                  catch ( SQLException e )
                  {
                        e.printStackTrace();
                  }
                  catch ( NumberFormatException e )
                  {
                        e.printStackTrace();
                  }
            }

            beanSync( bean, "deletion", null );
            beanSync( bean, "countrysel", countrysel );
            beanSync( bean, "regionsel", regionsel );
            beanSync( bean, "countysel", countysel );
            beanSync( bean, "townsel", townsel );
            beanSync( bean, "villagesel", villagesel );
      }

      protected void start_editing( ServletContext application,
                                    HttpServletRequest request, HttpServletResponse response )
            throws IOException, ServletException
      {
            super.start_editing( application, request, response );

            generateCommon( request, getCFService() );
      }

      /* (non-Javadoc)
       * @see ro.gateway.aida.srv.EditorServlet#other_action_performed(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String)
       */
      protected void other_action_performed( HttpServletRequest request,
                                             HttpServletResponse response, String action )
            throws IOException, ServletException
      {
            // TODO Auto-generated method stub
      }

      /* (non-Javadoc)
       * @see ro.gateway.aida.srv.EditorServlet#confirm(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
       */
      protected void confirm( HttpServletRequest request,
                              HttpServletResponse response ) throws IOException, ServletException
      {
            // TODO Auto-generated method stub
      }

      /* (non-Javadoc)
       * @see ro.gateway.aida.srv.EditorServlet#save(javax.servlet.ServletContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
       */
      protected void save( ServletContext application, HttpServletRequest request,
                           HttpServletResponse response ) throws IOException, ServletException
      {
            PersistenceToken token = PersistenceManager.tokenLookup( application );
            String param = HttpUtils.getValidTrimedString( request, "param", null ); //action parameter
            generateCommon( request, getCFService() );
            Hashtable bean = getBean( request );
            String error = null;

            //new region?
            if ( "newregion".equals( param ) )
            {
                  String newregion = HttpUtils.getValidTrimedString( request,
                        "newregion", null ); //new region to be added
                  String countrysel = HttpUtils.getValidTrimedString( request,
                        "countrylist", null ); //country select

                  if ( ( newregion != null ) && ( countrysel != null ) )
                  {
                        IIDGenerator idGenerators = ( IIDGenerator ) ( ( Hashtable ) application.getAttribute( Constants.SERVICES ) ).get( Constants.SERVICE_IDGEN );
                        Region r = new Region();
                        r.setId( ( int ) idGenerators.nextVal( Constants.IDGEN_REGIONS ) );
                        r.setName( newregion );
                        r.setCountryIso3( countrysel );
//                        RegionDB.getManager( token ).insertRegion( r );
                  }
            }

            //wanna delete old region?
            if ( "delregion".equals( param ) )
            {
                  String regionsel = HttpUtils.getValidTrimedString( request,
                        "regionlist", null ); //region select

                  if ( regionsel != null )
                  {
//                        try
//                        {
//                              if ( !RegionDB.getManager( token ).deleteRegion(
//                                    Integer.parseInt( regionsel ) ) )
//                                    error = "Region Delete: Cannot Delete! The region is not empty (counties assigned)";
//                              else
//                                    bean.put( "deletion", "region" );
//                        }
//                        catch ( NumberFormatException e )
//                        {
//                              e.printStackTrace();
//                        }
                  }

            }

            //new county?
            if ( "newcounty".equals( param ) )
            {
                  String newcounty = HttpUtils.getValidTrimedString( request,
                        "newcounty", null ); //new county to be added
                  String regionsel = HttpUtils.getValidTrimedString( request,
                        "regionlist", null ); //region select

                  if ( ( newcounty != null ) && ( regionsel != null ) )
                  {
                        IIDGenerator idGenerators = ( IIDGenerator ) ( ( Hashtable ) application.getAttribute( Constants.SERVICES ) ).get( Constants.SERVICE_IDGEN );
                        County j = new County();
                        j.setId( ( int ) idGenerators.nextVal( Constants.IDGEN_COUNTIES ) );
                        j.setName( newcounty );
                        j.setRegiune_id( Integer.parseInt( regionsel ) );
                        try
                        {
                              CountyDB.getManager( token ).insertCounty( j );
                        }
                        catch ( SQLException sqlEx )
                        {
                              sqlEx.printStackTrace();
                        }
                  }
            }

            //wanna delete old county?
            if ( "delcounty".equals( param ) )
            {
                  String countysel = HttpUtils.getValidTrimedString( request,
                        "countylist", null ); //county select
//                  if ( countysel != null )
//                  {
//                        try
//                        {
//                              if ( !CountyDB.getManager( token ).deleteCounty(
//                                    Integer.parseInt( countysel ) ) )
//                                    error = "County Delete: Cannot Delete! The county is not empty (towns assinged)";
//                              else
//                                    bean.put( "deletion", "county" );
//                        }
//                        catch ( NumberFormatException e )
//                        {
//                              e.printStackTrace();
//                        }
//
//                  }
            }

            //new town?
            if ( "newtown".equals( param ) )
            {
                  String newtownname = HttpUtils.getValidTrimedString( request,
                        "newtownname", null );
                  String newtownsirsupid = HttpUtils.getValidTrimedString( request,
                        "newtownsirsupid", null );
                  String newtowntype = HttpUtils.getValidTrimedString( request,
                        "newtowntype", null ); //
                  String countysel = HttpUtils.getValidTrimedString( request,
                        "countylist", null ); //county select

                  if ( ( newtownname != null ) && ( countysel != null ) )
                  {
                        Town o = new Town();
                        try
                        {
                              o.setSirsup_id( Integer.parseInt( newtownsirsupid ) );
                              o.setName( newtownname );
                              o.setJudet_id( Integer.parseInt( countysel ) );
                              o.setType( Byte.parseByte( newtowntype ) );
//                              TownDB.getManager( token ).insertTown( o );
                        }
                        catch ( NumberFormatException e )
                        {
                              error = "Town SIRSUP ID: Invalid Number Format!";

                        }


                  }
            }

            //delete town?
            if ( "deltown".equals( param ) )
            {
                  String townsel = HttpUtils.getValidTrimedString( request,
                        "townlist", null ); //town select

//                  if ( townsel != null )
//                  {
//                        try
//                        {
//                              if ( !TownDB.getManager( token ).deleteTown( Integer.parseInt( townsel ) ) )
//                                    error = "Town Delete: Cannot Delete! The town is not empty (villages assinged)";
//                              else
//                                    bean.put( "deletion", "town" );
//                        }
//                        catch ( NumberFormatException e )
//                        {
//                              e.printStackTrace();
//                        }
//                  }
            }


            //new village?
            if ( "newvillage".equals( param ) )
            {
                  String newvillagename = HttpUtils.getValidTrimedString( request,
                        "newvillagename", null );
                  String newvillagesirutaid = HttpUtils.getValidTrimedString( request,
                        "newvillagesirutaid", null );
                  String townsel = HttpUtils.getValidTrimedString( request,
                        "townlist", null ); //town select

                  if ( ( newvillagename != null ) && ( townsel != null ) )
                  {
                        Village l = new Village();
                        try
                        {
                              l.setSiruta_id( Integer.parseInt( newvillagesirutaid ) );
                              l.setName( newvillagename );
                              l.setSirsup_id( Integer.parseInt( townsel ) );
//                              VillageDB.getManager( token ).insertVillage( l );
                        }
                        catch ( NumberFormatException e )
                        {
                              error = "Village SIRUTA ID: Invalid Number Format!";

                        }


                  }
            }

            //delete village?
            if ( "delvillage".equals( param ) )
            {
                  String villagesel = HttpUtils.getValidTrimedString( request,
                        "villagelist", null ); //town select

//                  if ( villagesel != null )
//                  {
//                        try
//                        {
//                              VillageDB.getManager( token ).deleteVillage(
//                                    Integer.parseInt( villagesel ) );
//                        }
//                        catch ( NumberFormatException e )
//                        {
//                              e.printStackTrace();
//                        }
//                  }
                  bean.put( "deletion", "village" );
            }

            beanSync( bean, "error", error );
            generateCommon( request, getCFService() );
            reload( PV_SCR_EDIT, request, response );
      }

      /* (non-Javadoc)
       * @see ro.gateway.aida.srv.EditorServlet#edit(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
       */
      protected void edit( HttpServletRequest request, HttpServletResponse response )
            throws IOException, ServletException
      {
            generateCommon( request, getCFService() );

            reload( PV_SCR_EDIT, request, response );
      }

      /* (non-Javadoc)
       * @see ro.gateway.aida.srv.EditorServlet#getPNAME_BEANS()
       */
      public String getPNAME_BEANS()
      {
            return PNAME_BEANS;
      }

      /* (non-Javadoc)
       * @see ro.gateway.aida.srv.EditorServlet#getJSP_PAGE()
       */
      public String getJSP_PAGE()
      {
            return JSP_PAGE;
      }
}
